//
//  ATDemoTwoViewController.m
//  ATGaode_demo
//
//  Created by Chengquan Ye on 2019/3/5.
//  Copyright © 2019年 Chengquan Ye. All rights reserved.
//

#import "ATDemoTwoViewController.h"
#import <AMapTrackKit/AMapTrackKit.h>
#import <MAMapKit/MAMapKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapLocationKit/AMapLocationKit.h>
#import "ATQueyTrackViewController.h"
#import "ATStepNumberManager.h"

#import <SVProgressHUD.h>

#import "AMapRouteRecord.h"

#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height
#define iPhone4S [UIScreen mainScreen].bounds.size.height == 480
#define iPhone5S [UIScreen mainScreen].bounds.size.height == 568
#define iPhone6S [UIScreen mainScreen].bounds.size.height == 667
#define iPhonePlus [UIScreen mainScreen].bounds.size.height == 736
#define iPad ([UIScreen mainScreen].bounds.size.height > 736 && [UIScreen mainScreen].bounds.size.height != 812)
#define iPhoneX ([UIScreen mainScreen].bounds.size.height == 812 && [UIScreen mainScreen].bounds.size.width == 375)
#define iPhoneXR [UIScreen mainScreen].bounds.size.height == 896
#define iPhoneXS_MAX [UIScreen mainScreen].bounds.size.height == 896
#define iPhoneX_series (iPhoneX || iPhoneXR || iPhoneXS_MAX)

#define NavHeight (iPhoneX_series ? 88 : 64)
#define TabBarHeight (iPhoneX_series ? 83 : 49)
#define SafeBottomHeight (iPhoneX_series ? 34 : 0)

static NSString * const key = @"7cd0c6e32639e7ff175727a4f7e17ecc";
static NSString * const serviceName = @"轨迹测试服务";
static NSString * const clientName = @"轨迹测试终端";

static NSString * const sid = @"26335"; // 服务id
static NSString * const tid = @"26954385"; // 终端id

//28257710

@interface ATDemoTwoViewController () <AMapTrackManagerDelegate, MAMapViewDelegate, ATStepNumberManagerDelegate>

/** <#name#> */
@property (nonatomic, strong) AMapTrackManager *trackManager;

/** <#name#> */
@property (nonatomic, strong) ATStepNumberManager *stepNumberManager;

/** 高德地图view */
@property (nonatomic, strong) MAMapView *mapView;
/** 步数 */
@property (nonatomic, weak) UILabel *stepNumLbl;
/** 里程 */
@property (nonatomic, weak) UILabel *distanceLbl;

///新增的Track的ID
@property (nonatomic, strong) NSString *trackID;
///要查询的Terminal的ID
@property (nonatomic, copy) NSString *terminalID;

/** <#name#> */
@property (nonatomic, strong) NSTimer *timer;

/** 轨迹点数据数组 */
@property (nonatomic, strong) NSMutableArray<AMapTrackPoint *> *trackPointArray;

/** 开始时间 */
@property (nonatomic, strong) NSDate *startDate;
/** 结束时间 */
@property (nonatomic, strong) NSDate *endDate;


/** 开始记录 */
@property (nonatomic, assign) BOOL isRecording;
/** 结束记录 */
@property (nonatomic, assign) BOOL isEndRecording;


/** 前6个轨迹点*/
@property (nonatomic, assign) NSMutableArray *firstSixPointArray;


//@property (nonatomic, strong) MAMultiPolyline *mutablePolyline;
//@property (nonatomic, strong) MAMultiPointOverlayRenderer *mutableView;
//@property (nonatomic, strong) NSMutableArray *locationsArray;
//@property (nonatomic, strong) AMapRouteRecord *currentRecord;
//@property (nonatomic, strong) NSMutableArray *tracedPolylines;
//@property (nonatomic, strong) NSMutableArray *tempTraceLocations;
//@property (nonatomic, assign) double totalTraceLength;

@end

@implementation ATDemoTwoViewController

int pointCount = 0;

- (ATStepNumberManager *)stepNumberManager
{
    if (!_stepNumberManager) {
        _stepNumberManager = [ATStepNumberManager manager];
        _stepNumberManager.delegate = self;
    }
    return _stepNumberManager;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"猎鹰SDK";
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self setupUI];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"查询" style:UIBarButtonItemStylePlain target:self action:@selector(queryClick)];
    
    self.firstSixPointArray = [NSMutableArray array];
    [self initializeTrackManager];
    
    
    [self locationIsAvailable];
}

- (void)locationIsAvailable
{
    if ([CLLocationManager locationServicesEnabled] && ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorized || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways)) {
        //定位功能可用
        
    } else if ([CLLocationManager authorizationStatus] ==kCLAuthorizationStatusDenied) {
        //定位不能用
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请前往设置开启定位" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alertView show];
    }
}

#pragma mark - 初始化轨迹管理
- (void)initializeTrackManager
{
    AMapTrackManagerOptions *option = [[AMapTrackManagerOptions alloc] init];
    option.serviceID = sid; //Service ID 需要根据需要进行修改
    
    //初始化AMapTrackManager
    self.trackManager = [[AMapTrackManager alloc] initWithOptions:option];
    self.trackManager.delegate = self;
    
    // a.配置定位属性
    [self.trackManager setAllowsBackgroundLocationUpdates:YES];
    [self.trackManager setPausesLocationUpdatesAutomatically:NO];
    
    // b.配置定位采集周期和上报周期
    [self.trackManager changeGatherAndPackTimeInterval:2 packTimeInterval:10];
    
    // c.配置本地缓存大小
    [self.trackManager setLocalCacheMaxSize:50];
}

#pragma mark - 定时器相关
- (void)addTimer
{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

- (void)timerAction
{
    [self queryLastPoint];
    
    NSDate *endDate = [NSDate date];
    if (self.endDate) {
        endDate = self.endDate;
    }
    [self.stepNumberManager stepNumberWithStartDate:self.startDate endDate:endDate];
}

- (void)removeTimer
{
    [self.timer invalidate];
    self.timer = nil;
}

#pragma mark - 查询最新一个轨迹点
- (void)queryLastPoint
{
    AMapTrackQueryLastPointRequest *request = [[AMapTrackQueryLastPointRequest alloc] init];
    request.serviceID = self.trackManager.serviceID;
    request.terminalID = self.trackManager.terminalID;
//    request.correctionMode = @"denoise=1";
    [self.trackManager AMapTrackQueryLastPoint:request];
}

- (void)queryClick
{
    ATQueyTrackViewController *queryVc = [[ATQueyTrackViewController alloc] init];
    queryVc.trackID = self.trackID;
    queryVc.terminalID = self.terminalID;
    queryVc.startDate = self.startDate;
    queryVc.endDate = self.endDate;
    [self.navigationController pushViewController:queryVc animated:YES];
}

- (void)setupUI
{
    /*创建地图并添加到父view上*/
    self.mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, NavHeight, SCREEN_WIDTH, SCREEN_HEIGHT - NavHeight - SafeBottomHeight)];
    //    self.mapView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    self.mapView.delegate = self;
    [self.view addSubview:self.mapView];
    
    ///如果您需要进入地图就显示定位小蓝点，则需要下面两行代码
    self.mapView.showsUserLocation = YES;
    self.mapView.userTrackingMode = MAUserTrackingModeFollow;
    
    //    self.mapView.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
    //    self.mapView.distanceFilter = 5; // kCLDistanceFilterNone
    
//    self.mapView.pausesLocationUpdatesAutomatically = NO;
    
    // 不显示罗盘
    self.mapView.showsCompass = NO;
    
    // 不显示比例尺
    self.mapView.showsScale = NO;
    
    //是否自定义用户位置精度圈
    self.mapView.customizeUserLocationAccuracyCircleRepresentation = YES;
    MACircle *circle = [MACircle circleWithCenterCoordinate:self.mapView.userLocation.coordinate radius:0];
    [self.mapView addOverlay:circle];
    
    [self.mapView setZoomLevel:19];
//    [self.mapView setMaxZoomLevel:19];
    
    // 修改地图样式
    NSString *path = [NSString stringWithFormat:@"%@/style.data", [NSBundle mainBundle].bundlePath];
    NSData *styleData = [NSData dataWithContentsOfFile:path];
    MAMapCustomStyleOptions *styleOption = [[MAMapCustomStyleOptions alloc] init];
    styleOption.styleData = styleData;
    [self.mapView setCustomMapStyleOptions:styleOption];
    [self.mapView setCustomMapStyleEnabled:YES];
    
    UIButton *stopGatherBtn = [[UIButton alloc] init];
    stopGatherBtn.backgroundColor = [UIColor blackColor];
    stopGatherBtn.frame = CGRectMake(10, SCREEN_HEIGHT - 50, 150, 30);
    [stopGatherBtn addTarget:self action:@selector(stopGatherBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [stopGatherBtn setTitle:@"结束采集" forState:UIControlStateNormal];
    [self.view addSubview:stopGatherBtn];
    
    UIButton *startSerBtn = [[UIButton alloc] init];
    startSerBtn.frame = CGRectMake(10, stopGatherBtn.frame.origin.y - 50, 150, 30);
    startSerBtn.backgroundColor = [UIColor blackColor];
    [startSerBtn addTarget:self action:@selector(startSerBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [startSerBtn setTitle:@"开始服务和采集" forState:UIControlStateNormal];
    [self.view addSubview:startSerBtn];
    
    UILabel *stepNumLbl = [[UILabel alloc] init];
    stepNumLbl.frame = CGRectMake(CGRectGetMaxX(startSerBtn.frame) + 10, startSerBtn.frame.origin.y, SCREEN_WIDTH - (CGRectGetMaxX(startSerBtn.frame) + 10) - 10, 30);
    stepNumLbl.textAlignment = NSTextAlignmentRight;
    stepNumLbl.textColor = [UIColor whiteColor];
    stepNumLbl.backgroundColor = [UIColor blackColor];
    [self.view addSubview:stepNumLbl];
    self.stepNumLbl = stepNumLbl;
    
    UILabel *distanceLbl = [[UILabel alloc] init];
    distanceLbl.frame = CGRectMake(CGRectGetMaxX(startSerBtn.frame) + 10, stopGatherBtn.frame.origin.y, SCREEN_WIDTH - (CGRectGetMaxX(startSerBtn.frame) + 10) - 10, 30);
    distanceLbl.textAlignment = NSTextAlignmentRight;
    distanceLbl.textColor = [UIColor whiteColor];
    distanceLbl.backgroundColor = [UIColor blackColor];
    [self.view addSubview:distanceLbl];
    self.distanceLbl = distanceLbl;
}

#pragma mark - 点击结束采集
- (void)stopGatherBtnClick
{
    [self removeTimer];
    
    [self.trackManager stopGaterAndPack];
    
    self.endDate = [NSDate date];
    self.isRecording = !self.isRecording;
    self.isEndRecording = !self.isEndRecording;
}

#pragma mark - 点击开启服务和开启采集
- (void)startSerBtnClick:(UIButton *)button
{
    NSLog(@"点击开启服务按钮");
    //查询终端是否存在
    AMapTrackQueryTerminalRequest *request = [[AMapTrackQueryTerminalRequest alloc] init];
    request.serviceID = self.trackManager.serviceID;
    request.terminalName = @"测试终端1";
    [self.trackManager AMapTrackQueryTerminal:request];
    
//    [self startService:tid];
}

#pragma mark - 查询终端结果回调
- (void)onQueryTerminalDone:(AMapTrackQueryTerminalRequest *)request response:(AMapTrackQueryTerminalResponse *)response
{
    //查询成功
    if ([[response terminals] count] > 0) {
        //查询到结果，使用 Terminal ID
        NSString *terminalID = [[[response terminals] firstObject] tid];
        
        self.terminalID = terminalID;
        
        //启动上报服务(service id)，参考下一步
        NSLog(@"启动上报服务=---terminalID = %@", terminalID);
        
        [self startService:terminalID];
    }
    else {
        //查询结果为空，创建新的terminal
        AMapTrackAddTerminalRequest *addRequest = [[AMapTrackAddTerminalRequest alloc] init];
        addRequest.serviceID = self.trackManager.serviceID;
        addRequest.terminalName = @"测试终端2";
        [self.trackManager AMapTrackAddTerminal:addRequest];
    }
}

#pragma mark - 创建终端结果回调
- (void)onAddTerminalDone:(AMapTrackAddTerminalRequest *)request response:(AMapTrackAddTerminalResponse *)response {
    //创建terminal成功
    NSString *terminalID = [response terminalID];
    
    //启动上报服务(service id)，参考下一步
    NSLog(@"创建终端成功=---terminalID = %@", terminalID);
    self.terminalID = terminalID;
    
    if (response.code == AMapTrackErrorOK) {
        // 开始服务
        AMapTrackManagerServiceOption *serviceOption = [[AMapTrackManagerServiceOption alloc] init];
        serviceOption.terminalID = terminalID;//Terminal ID 需要根据需要进行修改
        [self.trackManager startServiceWithOptions:serviceOption];
    }
    
}

// 开启上报服务
- (void)startService:(NSString *)terminalID
{
    //开始服务
    AMapTrackManagerServiceOption *serviceOption = [[AMapTrackManagerServiceOption alloc] init];
    serviceOption.terminalID = terminalID;//Terminal ID 需要根据需要进行修改
    [self.trackManager startServiceWithOptions:serviceOption];
}

#pragma mark - 开启服务回调
//service 开启服务结果回调
- (void)onStartService:(AMapTrackErrorCode)errorCode {
    if (errorCode == AMapTrackErrorOK) {
        //开始服务成功，继续开启收集上报
        NSLog(@"开始服务成功--");
        
        [self doCreateTrackName];
        
//        [self.trackManager startGatherAndPack];
    } else {
        //开始服务失败
        NSLog(@"开始服务失败");
    }
}

#pragma mark - 开始采集结果回调
//gather 开启采集结果回调
- (void)onStartGatherAndPack:(AMapTrackErrorCode)errorCode {
    if (errorCode == AMapTrackErrorOK) {
        //开始采集成功
        NSLog(@"开始采集");
        [SVProgressHUD showSuccessWithStatus:@"开始采集"];
        
        self.trackPointArray = [NSMutableArray array];
        if (self.timer == nil) {
            [self addTimer];
        }
        
        self.startDate = [NSDate date];
        
        self.isRecording = YES;
        self.isEndRecording = NO;
        
    } else {
        //开始采集失败
        NSLog(@"开始采集失败");
    }
}

#pragma mark - 结束采集回调
- (void)onStopGatherAndPack:(AMapTrackErrorCode)errorCode {
    
    NSLog(@"结束采集:%ld", (long)errorCode);
    
    if (errorCode == AMapTrackErrorOK) { //
        [SVProgressHUD showSuccessWithStatus:@"结束采集"];
    }
}

#pragma mark - 结束服务回调
- (void)onStopService:(AMapTrackErrorCode)errorCode
{
    NSLog(@"结束服务:%ld", errorCode);
}

#pragma mark - 创建轨迹
- (void)doCreateTrackName {
    if (self.trackManager == nil) {
        return;
    }
    
    AMapTrackAddTrackRequest *request = [[AMapTrackAddTrackRequest alloc] init];
    request.serviceID = self.trackManager.serviceID;
    request.terminalID = self.trackManager.terminalID;
    [self.trackManager AMapTrackAddTrack:request];
}

#pragma mark - 创建轨迹结果回调
- (void)onAddTrackDone:(AMapTrackAddTrackRequest *)request response:(AMapTrackAddTrackResponse *)response
{
    //创建轨迹成功，开始采集
    self.trackID = response.trackID;
    NSLog(@"轨迹id =-== %@", response.trackID);
    
    if (response.code == AMapTrackErrorOK) {
        [SVProgressHUD showSuccessWithStatus:[NSString stringWithFormat:@"创建轨迹成功_---%@", response.trackID]];
        
        self.trackManager.trackID = self.trackID;
        [self.trackManager startGatherAndPack];
    } else {
        
    }
}

#pragma mark - 轨迹错误回调
- (void)didFailWithError:(NSError *)error associatedRequest:(id)request {
    NSLog(@"error === %@", error);
    if ([request isKindOfClass:[AMapTrackQueryTerminalRequest class]]) {
        //查询参数错误
        NSLog(@"查询参数错误");
    }
    
    if ([request isKindOfClass:[AMapTrackAddTerminalRequest class]]) {
        //创建terminal失败
        NSLog(@"创建terminal失败");
    }
    
    if ([request isKindOfClass:[AMapTrackAddTrackRequest class]]) {
        //创建轨迹失败
        NSLog(@"创建轨迹失败");
    }
    
    if ([request isKindOfClass:[AMapTrackQueryLastPointRequest class]]) {
        //查询失败
        NSLog(@"查询最新轨迹点失败");
    }
    
    if ([request isKindOfClass:[AMapTrackQueryTrackInfoRequest class]]) {
        NSLog(@"查询历史轨迹点失败");
    }
    
    if ([request isKindOfClass:[AMapTrackQueryTrackDistanceRequest class]]) {
        NSLog(@"查询历史轨迹里程失败");
    }
    
    if ([request isKindOfClass:[AMapTrackQueryTrackHistoryAndDistanceRequest class]]) {
        NSLog(@"查询历史轨迹点和里程失败");
    }
}

#pragma mark - 查询最新轨迹点回调
- (void)onQueryLastPointDone:(AMapTrackQueryLastPointRequest *)request response:(AMapTrackQueryLastPointResponse *)response
{
    //查询成功
    NSLog(@"onQueryLastPointDone====%f=====%f===%f", response.lastPoint.coordinate.latitude, response.lastPoint.coordinate.longitude, response.lastPoint.accuracy);
    
    pointCount++;
    
    if (pointCount < 6) {
        return;
    }
    
    if (self.trackPointArray.count > 1) {
        CLLocation *endLocation = [[CLLocation alloc] initWithLatitude:self.trackPointArray.lastObject.coordinate.latitude longitude:self.trackPointArray.lastObject.coordinate.longitude];
        
        CLLocation *currentLocation = [[CLLocation alloc] initWithLatitude:response.lastPoint.coordinate.latitude longitude:response.lastPoint.coordinate.longitude];
        
        double distance = [currentLocation distanceFromLocation:endLocation];
        
        NSLog(@"distance == %f", distance);
    }
    
    
    [self.trackPointArray addObject:response.lastPoint];
    [self.mapView removeOverlays:[self.mapView overlays]];
    [self showPolylineWithTrackPoints:self.trackPointArray];
}

#pragma mark - MAMapViewDelegate

- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation {
//    NSLog(@"userLocation == %f=---%f", userLocation.location.coordinate.latitude, userLocation.location.coordinate.longitude);
//
//    NSLog(@"定位位置改变-----%@", userLocation);
}

#pragma mark - Helper
- (void)showPolylineWithTrackPoints:(NSArray<AMapTrackPoint *> *)points {
    int pointCount = (int)[points count];
    
    CLLocationCoordinate2D *allCoordinates = (CLLocationCoordinate2D *)malloc(pointCount * sizeof(CLLocationCoordinate2D));
    for (int i = 0; i < pointCount; i++) {
        allCoordinates[i].latitude = [[points objectAtIndex:i] coordinate].latitude;
        allCoordinates[i].longitude = [[points objectAtIndex:i] coordinate].longitude;
    }
    
    MAPolyline *polyline = [MAPolyline polylineWithCoordinates:allCoordinates count:pointCount];
    [self.mapView addOverlay:polyline];
    
    if (allCoordinates) {
        free(allCoordinates);
        allCoordinates = NULL;
    }
}

#pragma mark - MapView Delegate

- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id<MAOverlay>)overlay {
    if ([overlay isKindOfClass:[MAPolyline class]]) {
        
        MAPolylineRenderer * polylineRenderer = [[MAPolylineRenderer alloc] initWithOverlay:overlay];
        polylineRenderer.lineWidth = 5.f;
        polylineRenderer.strokeColor = [UIColor greenColor];
        polylineRenderer.lineJoinType = kMALineJoinRound;
        polylineRenderer.lineCapType = kMALineCapRound;
        
        return polylineRenderer;
    }
    
    return nil;
}

#pragma mark - ATStepNumberManagerDelegate
- (void)stepNumber:(NSDictionary *)dict
{
    self.stepNumLbl.text = [NSString stringWithFormat:@"%@步", dict[@"numberOfSteps"]];
    self.distanceLbl.text = [NSString stringWithFormat:@"%@米", dict[@"distance"]];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
    // 返回删除定时器
    if (self.navigationController.topViewController == nil) {
        [self removeTimer];
    }
}

- (void)dealloc {
    [self.trackManager stopService];
    self.trackManager.delegate = nil;
    self.trackManager = nil;
    
    [self.mapView removeFromSuperview];
    self.mapView.delegate = nil;
    self.mapView = nil;
    
    NSLog(@"demoTwo----dealloc");
}

@end
